package com.pinc.wacow;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.pinc.wacow.R;

public class Category_View extends WidgetActivity {
	private ListView lv;
	private DBClass dbHelper;
	private Cursor mCursor;
	private Category_Adapter mAdapter;
	private int mMode;
	private long mGroupID;
	public static int MODE_NORMAL = 0;
	public static int MODE_ADD = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list_layout);
		mMode = getIntent().getIntExtra("mode", MODE_NORMAL);
		mGroupID = getIntent().getLongExtra("group_id", 0);
		initWidget();

		dbHelper = new DBClass(this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		mAdapter = new Category_Adapter(this);

		mCursor = dbHelper.getRecord(DBClass.TABLE_NAME_CATEGORY, null, null, "_id DESC", null);
		if (mCursor.moveToFirst())
		{
			do{
				Category_Class cc = new Category_Class(
						mCursor.getInt(mCursor.getColumnIndex("_id")),
						mCursor.getString(mCursor.getColumnIndex(DBClass.COL_QCTG_NAME)),
						(mMode == MODE_ADD)?dbHelper.getQuestionNoInCategoryNotInGroup(mCursor.getInt(mCursor.getColumnIndex("_id")), mGroupID):dbHelper.getQuestionNoInCategory(mCursor.getInt(mCursor.getColumnIndex("_id")))	
				);
				mAdapter.add(cc);
			}while(mCursor.moveToNext());
		}
		mCursor.close();
		dbHelper.mDB.close();

		/* Add All Question Item */
		//		mAdapter.addAll((mMode == MODE_ADD)?dbHelper.getQuestionNoInCategoryNotInGroup(-1, mGroupID):dbHelper.getQuestionNoInCategory(-1));

		lv.setAdapter(mAdapter);
		lv.setOnItemClickListener(new ItemClickListener());
	}

	@Override
	protected void initWidget() {
		super.initWidget();
		/* set upbar */
		tv_title.setText(getResources().getString(R.string.str_library));
		b_prev.setText(getResources().getString(R.string.str_back));
		b_prev.setVisibility(View.VISIBLE);
		b_prev.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});

		lv = (ListView) this.findViewById(R.id.listView1);
	}

	private class ItemClickListener implements OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,	long id) {
			Intent intent;
			if (mMode == MODE_NORMAL)
			{
				intent = new Intent(Category_View.this, Library.class);
			}
			else
			{
				intent = new Intent(Category_View.this, Library_Add.class);
				intent.putExtra("group_id", mGroupID);
			}
			intent.putExtra("id", id);
			intent.putExtra("title", mAdapter.getCategoryName(position));
			startActivity(intent);
		}
	}

}
